// 智能订单匹配算法模块
const pool = require('../config/database');

/**
 * 计算两点之间的距离（简化版，使用曼哈顿距离）
 * @param {String} location1 - 位置1
 * @param {String} location2 - 位置2
 * @returns {Number} 距离（米）
 */
function calculateDistance(location1, location2) {
  // 这里应该使用真实的地理坐标计算
  // 暂时返回随机距离作为示例
  // 实际应该调用地图API或使用坐标计算
  if (location1 === location2) return 0;
  // 简化处理：假设距离在100-2000米之间
  return Math.floor(Math.random() * 1900) + 100;
}

/**
 * 智能订单匹配算法
 * 基于距离优先、信用优先、效率优先等多策略匹配
 * @param {Object} order - 订单信息
 * @returns {Object} 匹配结果
 */
async function intelligentOrderMatching(order) {
  try {
    console.log('🎯 开始智能订单匹配，订单ID:', order.id);

    // 1. 获取所有在线且可接单的代拿员
    const [couriers] = await pool.execute(`
            SELECT 
                cu.*,
                u.nickname,
                u.phone,
                u.last_login_at,
                (SELECT COUNT(*) FROM orders o 
                 WHERE o.courier_user_id = cu.id 
                 AND o.status IN (2, 3)
                ) as current_orders
            FROM courier_users cu
            INNER JOIN users u ON cu.user_id = u.id
            WHERE cu.status = 'active' 
            AND u.account_status = 'active'
            AND (SELECT COUNT(*) FROM orders o 
                 WHERE o.courier_user_id = cu.id 
                 AND o.status IN (2, 3)
                ) < 3
            ORDER BY cu.credit_score DESC, cu.avg_rating DESC
        `);

    if (couriers.length === 0) {
      return {
        success: false,
        message: '暂无可用代拿员',
        matchedCouriers: []
      };
    }

    // 2. 计算每个代拿员的匹配分数
    const courierScores = couriers.map(courier => {
      let score = 0;

      // 信用分权重：40%
      const creditScoreWeight = (courier.credit_score / 100) * 40;
      score += creditScoreWeight;

      // 平均评分权重：30%
      const ratingWeight = ((courier.avg_rating || 5.0) / 5.0) * 30;
      score += ratingWeight;

      // 完成率权重：20%
      const completionRate = courier.completed_orders > 0
        ? courier.completed_orders / courier.total_orders
        : 0.5; // 新代拿员默认50%
      score += completionRate * 20;

      // 当前订单数权重：10%（当前订单越少，分数越高）
      const orderLoadWeight = (1 - (courier.current_orders / 3)) * 10;
      score += orderLoadWeight;

      // 距离因素（如果有位置信息）
      // 这里简化处理，实际应该使用真实距离
      const distanceFactor = 0; // 暂时不计算距离
      score += distanceFactor;

      return {
        courier: courier,
        score: score,
        creditScore: courier.credit_score,
        avgRating: courier.avg_rating || 5.0,
        completionRate: completionRate,
        currentOrders: courier.current_orders || 0
      };
    });

    // 3. 按分数排序
    courierScores.sort((a, b) => b.score - a.score);

    // 4. 选择前5名作为推荐代拿员
    const topCouriers = courierScores.slice(0, 5).map(item => ({
      courierId: item.courier.id,
      courierUserId: item.courier.user_id,
      nickname: item.courier.nickname,
      phone: item.courier.phone,
      score: parseFloat(item.score.toFixed(2)),
      creditScore: item.creditScore,
      avgRating: item.avgRating,
      matchReason: generateMatchReason(item)
    }));

    console.log('✅ 订单匹配完成，找到', topCouriers.length, '位推荐代拿员');

    return {
      success: true,
      message: '匹配成功',
      matchedCouriers: topCouriers,
      matchingStrategy: 'multi-factor'
    };

  } catch (error) {
    console.error('❌ 智能订单匹配失败:', error);
    return {
      success: false,
      message: '匹配失败: ' + error.message,
      matchedCouriers: []
    };
  }
}

/**
 * 生成匹配原因说明
 */
function generateMatchReason(courierScore) {
  const reasons = [];
  if (courierScore.creditScore >= 90) reasons.push('高信用');
  if (courierScore.avgRating >= 4.5) reasons.push('高评分');
  if (courierScore.currentOrders === 0) reasons.push('空闲中');
  if (courierScore.completionRate >= 0.9) reasons.push('高完成率');
  return reasons.length > 0 ? reasons.join('、') : '推荐代拿员';
}

/**
 * 自动派单（为订单自动分配给最优代拿员）
 * @param {Number} orderId - 订单ID
 * @returns {Object} 派单结果
 */
async function autoAssignOrder(orderId) {
  try {
    // 1. 获取订单信息
    const [orders] = await pool.execute(
      'SELECT * FROM orders WHERE id = ? AND status = 1',
      [orderId]
    );

    if (orders.length === 0) {
      return {
        success: false,
        message: '订单不存在或已被接单'
      };
    }

    const order = orders[0];

    // 2. 执行智能匹配
    const matchingResult = await intelligentOrderMatching(order);

    if (!matchingResult.success || matchingResult.matchedCouriers.length === 0) {
      return {
        success: false,
        message: '暂无可用代拿员',
        autoAssigned: false
      };
    }

    // 3. 自动分配给分数最高的代拿员
    const bestCourier = matchingResult.matchedCouriers[0];

    // 4. 更新订单状态
    await pool.execute(
      'UPDATE orders SET courier_user_id = ?, status = 2, accepted_at = NOW() WHERE id = ?',
      [bestCourier.courierId, orderId]
    );

    // 5. 更新代拿员统计
    await pool.execute(
      'UPDATE courier_users SET total_orders = total_orders + 1 WHERE id = ?',
      [bestCourier.courierId]
    );

    console.log('✅ 自动派单成功，订单ID:', orderId, '代拿员ID:', bestCourier.courierId);

    return {
      success: true,
      message: '自动派单成功',
      autoAssigned: true,
      courier: {
        courierId: bestCourier.courierId,
        nickname: bestCourier.nickname,
        phone: bestCourier.phone
      }
    };

  } catch (error) {
    console.error('❌ 自动派单失败:', error);
    return {
      success: false,
      message: '自动派单失败: ' + error.message,
      autoAssigned: false
    };
  }
}

module.exports = {
  intelligentOrderMatching,
  autoAssignOrder,
  calculateDistance
};

